import React, { useState, useMemo } from 'react';
import s from '../style.module.css';
import Breadcrumb, { Item } from '../../../../../components/Breadcrumb';
import Helper from '../../../../../components/Helper';
import { withRouter } from 'react-router';
import cn from 'classnames'
import SecurityRating from '../SecurityRating';
import { IconS, Download } from '../SecurityRating/picture';
import PropTypes from 'prop-types';
import Label from '../../../../../components/Label';
import Select from '@knownsec/react-component/dist/Select';
import fetchFer from 'API/fetch';
import Message from '@knownsec/react-component/dist/Message'
import Button from '@knownsec/react-component/dist/Button'
import Tooltip from '@knownsec/react-component/dist/Tooltip'
import Icon from '@knownsec/react-component/dist/Icon'
import { turnToUrlparam, GetQueryString } from '../../../../../helpers/getUrlParams';
import { datetime,timeChange } from '../../../../../../common/formatter';
import moment from 'moment'
import SequenceDialog, { SequenceIcon } from '../../../../../components/SequenceDialog';
import WafErrorDialog from '../../../../../components/WafErrorDialog';
import UrlDetailDialog from '../../../../../components/UrlDetailDialog';

import WebTaskDetail from '../WebTaskDetail';
import _, { cloneDeep } from 'lodash';
const infoObj = {
	target_url: '资产地址',
	target_ip: '响应IP',
	url_count: '检测URL数',
	scan_count: '检测次数',
	target_status: <span>网络状态<Tooltip placement='top' overlay='最近一次监测任务的网络检测结果'><Icon type='question' className={'cp'} /></Tooltip></span>,
	waf_info: '防御信息',
	result: '监测结果'
};
const statusMap = {
	http_waf_error:
		<span>
			ScanV扫描节点疑似被目标主机防火墙拦截，建议将
			<WafErrorDialog />
			加白再进行检测。
		</span>,
	http_status_error: '平台探测到疑似网站状态异常，建议检查网站状态。',
	http_code_error: '平台探测到网站状态码异常，建议检查网站状态。',
	ping_error: '平台探测到疑似目标主机服务异常，建议检查服务状态。',
};
const taskMap = {
	vul: 'Web漏洞',
	ssl: 'SSL安全威胁',
	security_event: '安全事件',
	content: '内容违规',
	change_check: '篡改事件'
}
const taskSubMap = {
	vul: {
		critical: '严重',
		high: '高危',
		medium: '中危',
		low: '低危'
	}
}
const taskMsgMap = {
	vul: '漏洞隐患',
	ssl: 'SSL安全隐患',
	security_event: '安全事件隐患',
	content: '违规内容信息',
	change_check: '篡改事件'
}
const taskTypeNameMap = {
	"change_check": "changeCheck",
	"security_event": "securityEvent",
}
const vulMap = {
	xc_products: '21',
	ssl_certificate: '19',
	ssl_protocol: '20',
	configuration: '9',
	information_disclosure: '15',
	directory_traversal: '12',
	file_inclusion: '13',
	command_execution: '8',
	file_upload: '14',
	injection: '16',
	code_execution: '7',
	csrf: '10',
	directory_listing: '11',
	malware: '17',
	webvul: '18',
	normal: '5',
	high_risk: '2',
	sql_injection: '3',
	xss: '4',
	full: '1'
}
function History({
	match: {
		params: { assetType, jid },
	},
	location,
}) {
	const atid = GetQueryString(location.search, 'id');
	const type = GetQueryString(location.search, 'type');
	const last = GetQueryString(location.search, 'last');
	const task_types = GetQueryString(location.search, 'task_types');
	const asset_task_id = GetQueryString(location.search, 'asset_task_id');
	const task_id = GetQueryString(location.search, 'task_id');
	const [selVal, setSelVal] = useState([]);
	const [timeOpt, setTimeOpt] = useState([]);
	const [manualT, setManualT] = useState();
	const [detail, setDetail] = useState([{}]);
	const [loading, setLoading] = useState(false)
	const [overview, setOverview] = useState(null)
	const getHistoryDetail = async () => {
		setLoading(true)
		const sendData = {
			task_types,
			asset_task_id,
			task_id: selVal[0]
		};
		const params = turnToUrlparam(sendData);
		const res = await fetchFer(
			`/api/v2/tasks/web_security/type/detail?${params}`,
			{
				method: 'GET',
			}
		);
		if (res.code === 200) {
			const data = cloneDeep(res.data)
			data.settings = data.task_settings
			if (task_types === 'vul') {
				data.settings.collect.vul = data?.task_settings?.collect?.vul?.map(item => {
					if (vulMap[item]) {
						return vulMap[item]
					} else {
						return item
					}
				})
			}
			const scoreInfo = res.data?.score_info
			const total = scoreInfo?.count || 0
			const overV = data?.overview
			overV.score = scoreInfo.score
			overV.url_count = overV.url_count + ''
			overV.result = '发现'
			if (total) {
				overV.result += total + '个' + (task_types === 'content' ? '地址存在违规内容' : taskMap[task_types])
				if (taskSubMap[task_types]) {
					overV.result += '，其中'
					overV.result += Object.keys(taskSubMap[task_types]).reduce((t, key) => {
						// if (scoreInfo[key]) {
							t.push(taskSubMap[task_types][key] + (scoreInfo[key] || 0) + '个')
						// }
						return t
					}, []).join('，')
				}
				overV.result += '，为了您的资产安全，请及时修复并加固安全防护。'
			} else {
				overV.result = `未发现${taskMsgMap[task_types]}，您的资产处于安全状态。`
			}
			setOverview(overV)
			setDetail(data);
			setLoading(false)
		} else {
			Message.show({ type: res.status, message: res.message })
		}
	};
	const resDemo = e => {
		const aa = e && e.replace(/\d+/g, `<span style='color: #EA0028'>$&</span>`);
		return aa;
	};
	// 获取时间列表
	useMemo(async () => {
		const sendData = {
			task_types: taskTypeNameMap.hasOwnProperty(task_types) ? _.get(taskTypeNameMap, task_types) : task_types,
			asset_task_id
		};
		const params = turnToUrlparam(sendData);
		const res = await fetchFer(`/api/v2/repodatas/task_completed_times?${params}`, {
			method: 'GET',
		}).catch(error => {
			return error;
		});
		const time = res.data.map(e => {
			const differenceTime = Date.now() - new Date(datetime(e.time)).getTime();
			if (e.id === task_id) {
				setManualT(datetime(e.time));
				setSelVal([e.id]);
			}
			return {
				label:
					moment(e.time).format('YYYY-MM-DD HH:mm:ss') +
					`（${timeChange(differenceTime)}前）`,
				labelHtml: `<p style="display:flex"><span style="width: 150px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">${datetime(
					e.time
				)}</span>
			<span style="width: 85px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">(${timeChange(
				differenceTime
			)}前)</span></p>`,
				value: e.id,
			};
		});
		setTimeOpt(time);
		!last && setSelVal([time[0].value]);
	}, [assetType]);

	const [downloadTimer, setDownloadTimer] = React.useState(false);
	const downloadReport = () => {
		if (downloadTimer) return false;
		setDownloadTimer(true);
		const text = `[${overview.job_name}]ScanV安全监测报告.docx`;
		fetch(`/api/v2/report/one_task/download?task_id=${selVal[0]}`, {
			method: 'GET',
		}).then(res => {
			if (res.ok) {
				return res.blob();
			}
		})
		.then(blob => {
			const url = (window.webkitURL || window.URL).createObjectURL(blob);
			const a = document.createElement('a');
			a.href = url;
			a.download = text;
			a.click();
			setDownloadTimer(false);
		})
		.catch(() => {
			Message.show({
				type: 'error',
				message: `导出${text}`,
				placement: 'top',
				style: { width: '25rem' },
			});
			setDownloadTimer(false);
		});
	}

	React.useEffect(() => {
		if (selVal.length > 0) getHistoryDetail();
	}, [selVal]);
	const [refresh, setRefresh] = useState(false)
	React.useEffect(() => {
		if (refresh) {
			getHistoryDetail();
		}
	}, [refresh]);
	return (
		<div className={s.taskMain}>
			<div className='df aic jcsb pr24'>
				<Breadcrumb>
					<Item key="job-manage" disabled>
						任务管理
					</Item>
					<Item key="web-task">Web安全监测</Item>
					<Item key={`detail?id=${asset_task_id}&type=schedule&tag=${task_types}`}>监测结果</Item>
					<Item key="">历史任务</Item>
				</Breadcrumb>
				<div className={cn(s.df, s.aic, s.w440)}>
					<div className={cn(s.df, s.aic, s.fs20)}>
						历史监测结果:
						<Select
							pro
							value={selVal}
							placeholder="检测历史"
							option={timeOpt}
							className={cn(s.sel, s.m0_10_0_5, s.w210)}
							clearable
							onChange={({ selectedItem }) => {
								setSelVal([selectedItem[0].value]);
							}}
						/>
					</div>
					{detail?.job_id && <Button pro className={s.downloadPlain} onClick={downloadReport}>
						<svg width="20px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">
								<g id="控件" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
										<g id="Web安全任务详情表头" transform="translate(-1052.000000, -33.000000)" fill-rule="nonzero">
												<g id="编组-3" transform="translate(1032.000000, 25.000000)">
														<g id="下载" transform="translate(20.000000, 8.000000)">
																<rect id="矩形" fill="#000000" opacity="0" x="0" y="0" width="20" height="20"></rect>
																<path d="M16.3636364,17.9545454 L3.63636363,17.9545454 C2.75772881,17.9545454 2.04545455,17.2422712 2.04545455,16.3636364 L2.04545455,14.5454546 C2.04545455,14.1688968 2.35071495,13.8636364 2.72727273,13.8636364 C3.10383052,13.8636364 3.40909092,14.1688968 3.40909092,14.5454546 L3.40909092,16.3636364 C3.40909093,16.4891556 3.51084438,16.5909091 3.63636363,16.5909091 L16.3636364,16.5909091 C16.4891556,16.5909091 16.5909091,16.4891556 16.5909091,16.3636364 L16.5909091,14.5454546 C16.5909091,14.1688968 16.8961695,13.8636364 17.2727273,13.8636364 C17.6492851,13.8636364 17.9545454,14.1688968 17.9545454,14.5454546 L17.9545454,16.3636364 C17.9545454,17.2422712 17.2422712,17.9545454 16.3636364,17.9545454 L16.3636364,17.9545454 Z M10,12.5090909 C9.81758439,12.5090909 9.64276921,12.4360263 9.51463893,12.3061877 C9.38650865,12.176349 9.31574961,12.0005812 9.31818182,11.8181818 L9.31818182,2.72727273 C9.31818182,2.35071495 9.62344222,2.04545455 10,2.04545455 C10.3765578,2.04545455 10.6818182,2.35071495 10.6818182,2.72727273 L10.6818182,11.8181818 C10.6842504,12.0005812 10.6134913,12.176349 10.4853611,12.3061877 C10.3572308,12.4360263 10.1824156,12.5090909 10,12.5090909 L10,12.5090909 Z M10,13.6772727 C9.81933074,13.6766185 9.64620538,13.6047552 9.51818182,13.4772727 L4.97272727,8.93181818 C4.84392179,8.80457551 4.77142679,8.63105676 4.77142679,8.45 C4.77142679,8.26894324 4.84392179,8.09542449 4.97272727,7.96818182 C5.23994534,7.70479205 5.66914556,7.70479205 5.93636363,7.96818182 L10.4818182,12.5136364 C10.6106237,12.640879 10.6831187,12.8143978 10.6831187,12.9954546 C10.6831187,13.1765113 10.6106237,13.3500301 10.4818182,13.4772727 C10.3537946,13.6047552 10.1806693,13.6766185 10,13.6772727 Z M10,13.6772727 C9.81933074,13.6766185 9.64620538,13.6047552 9.51818182,13.4772727 C9.38937634,13.3500301 9.31688134,13.1765113 9.31688134,12.9954546 C9.31688134,12.8143978 9.38937634,12.640879 9.51818182,12.5136364 L14.0636364,7.96818182 C14.3308544,7.70479205 14.7600547,7.70479205 15.0272727,7.96818182 C15.1560782,8.09542449 15.2285732,8.26894324 15.2285732,8.45 C15.2285732,8.63105676 15.1560782,8.80457551 15.0272727,8.93181818 L10.4818182,13.4772727 C10.3537946,13.6047552 10.1806693,13.6766185 10,13.6772727 L10,13.6772727 Z" id="形状" fill="#0B6FD6"></path>
														</g>
												</g>
										</g>
								</g>
						</svg>
						下载报告
					</Button>}
				</div>
			</div>
			<div className={cn(s.content, s.pt0)}>
				<div className={s.header}>
					<div className={s.left}>
						<SecurityRating score={detail?.score_info?.level === '未知' ? undefined : (100 - (overview?.score || 0))} />
					</div>
					<div className={s.right}>
					<div className={cn(s.mb16)}>
						<div className={s.title} title={overview?.name}>
							任务名称：{overview?.name}
						</div>
					</div>
						<div className={s.info}>
							<div className={cn(s.df, s.aic, 'fww')}>
								{Object.keys(infoObj).slice(0, 6).map((e, i) => {
									return (e === 'url_count' && detail?.overview?.is_display_url || e !== 'url_count') && <div className={cn('w50p df aic mb16')} key={e}>
										<span className={s.infoName}>{infoObj[e]}</span>：
										<span className={s.infoVal}>
											{e === 'url_count' ? <>
												{overview && overview[e]}
												{detail?.overview?.task_type !== 'ssl' && <UrlDetailDialog id={detail?.task_id} overview={detail?.overview} type='task' className={'ml5'} />}
											</> : e === 'target_status' ? <span className={cn({'success-color': detail[e]?.httpGetSequence && detail[e]?.status === 'good', 'error-color': detail[e]?.httpGetSequence && detail[e]?.status !== 'good'}, 'df aic')}>
												{detail[e]?.httpGetSequence ? detail[e]?.status === 'good' ?
												<>{SequenceIcon['正常']}正常</> :
												<>{SequenceIcon['异常']}异常</> : '- -'}<SequenceDialog className={'ml5'} target_status={{
														http: {...detail[e]?.httpGetSequence, target_status: detail[e]?.httpGetSequence ? detail[e]?.status : '' },
														ping: {...detail[e]?.detailPing, target_status: detail[e]?.detailPing ? detail[e]?.status : '' },
													}}
													title={<span>
														{/* <span className='main-color'></span> */}
														{taskMap[task_types]}网络快照
													</span>}
													subTitle=''
													url_count={detail?.overview?.url_count} statusText={statusMap[detail[e]?.status] ? detail[e]?.status : (detail[e]?.status === 'good' ? '正常' : '')}
											 />
											</span> : <>{(overview && overview[e]) || '- -'}</>}
										</span>
									</div>
								})}
							</div>
							{Object.keys(infoObj).slice(6).map(e => {
								return (
									<div className={s.rBox}>
										<p className={cn(s.df, s.aic)}>
											<IconS />
											<span className={s.ml12}>{infoObj[e]}</span>
										</p>
										{detail?.score_info?.level === '未知' && statusMap[detail?.target_status?.status] ? <p>
												{`您的资产安全处于${detail?.score_info?.level}状态，`}
												{statusMap[detail?.target_status?.status]}
											</p> : <p
											dangerouslySetInnerHTML={{ __html: resDemo((overview && overview[e]) || '') }}
											className={s.infoVal}
										></p>}
									</div>
								);
							})}
						</div>
					</div>
				</div>
				<div className={s.infoBody}>
					<Label className={s.labelDetail}>监测详情</Label>
					<div className={s.pr}>
						<WebTaskDetail refresh={setRefresh} webDataLoading={loading} taskType={'schedule'} task_types={task_types} data={{ task_id, [task_types]: detail, task_settings: detail.task_settings }} tid={selVal} atid={asset_task_id} isHistory={true} />
					</div>
				</div>
			</div>
		</div>
	);
}
History.propTypes = {
	location: PropTypes.any,
	match: PropTypes.shape({
		params: PropTypes.shape({
			assetType: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
};
export default withRouter(History);
